package cn.sanch.basic.loginContext;

import cn.sanch.basic.jwt.JwtUtils;
import cn.sanch.basic.jwt.LoginData;
import cn.sanch.basic.jwt.Payload;
import cn.sanch.basic.jwt.RsaUtils;
import cn.sanch.user.domain.Logininfo;

import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;

/**
 * 获取登录人的登录信息
 *
 * @author sanch37
 * 2022/6/15
 */
public class LoginContext {

    public static Logininfo getLogininfo(HttpServletRequest request) {
        // 1.获取token
        String token = request.getHeader("token");
        // 2.判断token不为空
        if (token != null){

            try {
                // 3.获取公钥
                PublicKey publicKey = RsaUtils.getPublicKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
                // 4.解密
                Payload<LoginData> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginData.class);
                // 5.返回登录人的登录信息
                return payload.getLoginData().getLogininfo();

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        return null;

    }

}
